//
//  SignleModelHandler.m
//  GroupDeal
//
//  Created by lewang on 14-7-31.
//  Copyright (c) 2014年 groupdeal. All rights reserved.
//
#import "DataHandler.h"
#import "SignleModelHandler.h"
#import "AppDelegate.h"
#import "USER_INFO.h"
#import "ShareUserModel.h"

static SignleModelHandler *_signleModelHandler;

@implementation SignleModelHandler


- (instancetype)init
{
    self = [super init];
    if (self)
    {
        // Register context with the notification center
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self
               selector:@selector(mergeChanges:)
                   name:NSManagedObjectContextDidSaveNotification
                 object:self.objectContext];
        
    }
    return self;
}

+(SignleModelHandler *)shareSignleModelHandler
{
    @synchronized(self){
        if (!_signleModelHandler) {
            _signleModelHandler = [[SignleModelHandler alloc] init];
        }
    }
    
    return _signleModelHandler;
}


+(id)allocWithZone:(NSZone *)zone{
    
    @synchronized(self)
    {
        if (!_signleModelHandler) {
            _signleModelHandler = [super allocWithZone:zone];
            return _signleModelHandler;
        }
    }
    
    return nil;
}


#pragma mark  -  数据合并 
- (void)mergeChanges:(NSNotification *)notification
{
    AppDelegate  *appdelegate = ((AppDelegate*)[[UIApplication sharedApplication] delegate]);
    NSManagedObjectContext *mainContext = [appdelegate managedObjectContext];
    
    // Merge changes into the main context on the main thread
    [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                                  withObject:notification
                               waitUntilDone:YES];
}

#pragma mark -  用户登录信息

//插入用户信息
-(void)InsertUserInfo:(USER_INFO *)user
{
    
    [[self objectContext] performBlock:^
     {
         NSError *error = nil;
         NSArray *arrReturn = nil;
         
         //创建取回数据请求
         NSFetchRequest *request = [[NSFetchRequest alloc] init];
         //设置要检索哪种类型的实体对象
         NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:self.objectContext];
         
         [request setEntity:entity];//设置请求实体
         arrReturn = [self.objectContext executeFetchRequest:request error:&error];
         if (error == nil)
         {
             //删除旧数据
             if ( [arrReturn count] > 0  && [[arrReturn objectAtIndex:0] isKindOfClass:[USER_INFO class]])
             {
                 for (NSManagedObject *object in arrReturn)
                 {
                     
                     [self.objectContext deleteObject:object];
                 }
             }
         }
         
         [DataHandler copyObject:user toContext:self.objectContext];//转临时为固定
         [self saveContext];
     }];
}

//更新用户密码,用于自动登录
//-(void)UpdateUserPwd:(NSString  *)strPasswd
//{
//    
//    [[self objectContext] performBlock:^
//     {
//         NSError *error = nil;
//         NSArray *arrReturn = nil;
//         
//         //创建取回数据请求
//         NSFetchRequest *request = [[NSFetchRequest alloc] init];
//         //设置要检索哪种类型的实体对象
//         NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:self.objectContext];
//         
//         [request setEntity:entity];//设置请求实体
//         arrReturn = [self.objectContext executeFetchRequest:request error:&error];
//         if (error == nil)
//         {
//             //删除旧数据
//             if ( [arrReturn count] > 0  && [[arrReturn objectAtIndex:0] isKindOfClass:[USER_INFO class]])
//             {
//                 for (USER_INFO *object in arrReturn)
//                 {
//                     [object setUserPwd:strPasswd];
////                     [self.objectContext deleteObject:object];
//                 }
//             }
//         }
//         
//         [self saveContext];
//     }];
//}


//清理用户信息
-(BOOL)ClearUserInfo
{
    __block BOOL bResult = NO;
    
    [[self objectContext] performBlock:^
     {
         NSError *error = nil;
         NSArray *arrReturn = nil;
         
         //创建取回数据请求
         NSFetchRequest *request = [[NSFetchRequest alloc] init];
         //设置要检索哪种类型的实体对象
         NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:self.objectContext];
         
         [request setEntity:entity];//设置请求实体
         arrReturn = [self.objectContext executeFetchRequest:request error:&error];
         if (error == nil)
         {
             bResult = YES;
             //删除旧数据
             if ( [arrReturn count] > 0  && [[arrReturn objectAtIndex:0] isKindOfClass:[USER_INFO class]])
             {
                 for (NSManagedObject *object in arrReturn)
                 {
                     
                     [self.objectContext deleteObject:object];
                 }
             }
         }
         
         [self saveContext];
         
     }];
    
    
    
    return bResult;
}

//查询上次登录记录
- (USER_INFO *)UserLastLogin
{
    __block USER_INFO *userReturn = nil;
    [self.objectContext performBlockAndWait:^
    {
        
        NSError *error = nil;
        NSArray *arrReturn = nil;
        //创建取回数据请求
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        
        //设置要检索哪种类型的实体对象
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"USER_INFO" inManagedObjectContext:self.objectContext];
        [request setEntity:entity];//设置请求实体
        
        arrReturn = [self.objectContext executeFetchRequest:request error:&error];
        if (error == nil)
        {
            if (   [arrReturn count] > 0
                && [[arrReturn objectAtIndex:0] isKindOfClass:[USER_INFO class]])
            {
                userReturn = [arrReturn objectAtIndex:0];
            }
        }
    }];
    
    return userReturn;
}


#pragma mark  - 主要参数
-(NSManagedObjectContext *)objectContext
{

            if (_objectContext != nil) {
        return _objectContext;
    }
    
    AppDelegate *appdelegate = ((AppDelegate*)[[UIApplication sharedApplication] delegate]);
    if (appdelegate.managedObjectContext != nil)
    {
        _objectContext= [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [_objectContext setParentContext:(NSManagedObjectContext *)[appdelegate persistentStoreCoordinator]];
    }
    
    return _objectContext;
}



- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.objectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }else
        {
            NSLog(@"保存成功");
        }
    }
}



@end
